package com.xsmart.oa.services;


import com.google.gson.Gson;
import com.xsmart.common.constant.ResultConstant;
import com.xsmart.common.entity.RequestBean;
import com.xsmart.common.entity.ResponseBean;
import com.xsmart.common.services.LoginTokenService;
import com.xsmart.common.util.HttpClientUtil;
import com.xsmart.oa.dao.wx.UserInfoDao;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author chenzb
 * @create 2018-01-09 下午4:44
 **/
@Service
public class WxmanageService {


    @Value("${app.login-credential.request-url}")
    private String credentialRequestUrl;

    public static final String APP_ID = "APPID";
    public static final String APPSECRET = "APPSECRET";


    @Autowired
    LoginTokenService loginTokenService;

    @Autowired
    private UserInfoDao userInfoDao;

    /**
     * 开发者服务器使用登录凭证 code 获取 session_key 和 openid
     *
     * @param requestBean
     * @return
     */
    public ResponseBean getOpenIdAndSessionKey(RequestBean requestBean) {


        String credentialCode = requestBean.getRequestParamString("credentialCode");
        //测试数据会出现空格，先处理掉，后续正式上线要修改掉
        credentialCode = credentialCode.replaceAll(" ","");
        String url = credentialRequestUrl + "appid=" + getSysParamVal(APP_ID) + "&secret=" + getSysParamVal(APPSECRET) + "&js_code=" + credentialCode + "&grant_type=authorization_code";

        String reponseResult = HttpClientUtil.doPost(url, "", "utf-8");

        Gson gson = new Gson();
        Map resultMap = gson.fromJson(reponseResult, Map.class);
        Object errCodeObj = MapUtils.getObject(resultMap,"errcode");
        ResponseBean responseBean = requestBean.getResponseBean();
        String token = loginTokenService.generalTokenStr();
        responseBean.setToken(token);
        if (errCodeObj != null){
            responseBean.setResult(ResultConstant.ERROR);
            responseBean.setMessage(MapUtils.getString(resultMap,"errmsg"));
        }else {
            responseBean.setResult(ResultConstant.SUCCESS);
            responseBean.setResultData(resultMap);
        }
        return responseBean;
    }


    private String getSysParamVal(String paramCode){
        Map<String,Object> paramMap = userInfoDao.findByParamCode(paramCode);
        return MapUtils.getString(paramMap,"param_value");
    }
}